<template>
  <div class="box">
    <el-card style="margin: 20px">
      <!-- 查询表单 -->
      <el-form :inline="true" class="demo-form-inline">
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属栏目">
              <el-select
                clearable
                v-model="searchList.columnId"
                placeholder="请选择"
                style="width: 200px"
                size="medium "
              >
                <el-option
                  v-for="column in columnList"
                  :key="column.id"
                  :label="column.columnName"
                  :value="column.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8"
            ><el-form-item label="状态">
              <el-select
                clearable
                v-model="searchList.releaseStatus"
                placeholder="请选择"
                style="width: 200px"
                size="medium "
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="未发布" value="1"></el-option>
                <el-option label="已发布" value="2"></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-button type="primary" size="medium " @click="search"
              >查询</el-button
            >
            <el-button type="primary" size="medium " @click="addNews"
              >添加新闻</el-button
            >
            <el-button type="primary" size="medium " @click="deleteInBatches"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin: 20px">
      <!-- 表格
        @selection-change="handleSelectionChange"
       -->
      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
        :data="list"
        border
        :header-cell-style="{ background: '#ebeef5' }"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column
          :prop="item.prop"
          v-for="(item, index) in tableList"
          :key="index"
          :label="item.label"
          :width="item.width"
        >
        </el-table-column>
        <el-table-column prop="releaseStatus" label="状态" width="100">
          <template slot-scope="{ row }">
            {{ row.releaseStatus == 1 ? "未发布" : "已发布" }}
          </template></el-table-column
        >
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              :icon="
                row.releaseStatus == 1 ? 'el-icon-success' : 'el-icon-error'
              "
              @click="release(row)"
              >{{ row.releaseStatus == 1 ? "发布" : "取消发布" }}</el-button
            >
            <el-button type="text" icon="el-icon-edit" @click="editNews(row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确认删除这条新闻吗？"
              @confirm="deleteJourn(row)"
            >
              <el-button type="text" slot="reference" icon="el-icon-delete"
                >删除</el-button
              >
            </el-popconfirm>
            <el-button
              type="text"
              icon="el-icon-setting"
              @click="carousel(row)"
              >{{
                row.carouselStatus == 1 ? "设为轮播图" : "取消轮播图"
              }}</el-button
            >
            <el-button
              type="text"
              :icon="row.topStatus == 1 ? 'el-icon-top' : 'el-icon-bottom'"
              @click="topOrBottom(row)"
              >{{
                row.topStatus == 1 ? "设为置顶新闻" : "取消置顶新闻"
              }}</el-button
            >
            <el-button
              type="text"
              :icon="row.privacy == 1 ? 'el-icon-lock' : 'el-icon-unlock'"
              @click="encryption(row)"
              >{{ row.privacy == 1 ? "设为私密" : "设为公开" }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加与编辑弹窗 -->
      <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="77%"
        :before-close="handleClose"
      >
        <el-form
          ref="ruleFrom"
          label-width="400px"
          :model="formList"
          :rules="rules"
        >
          <el-form-item label="输入子栏目" prop="title">
            <el-input
              v-model="formList.title"
              style="width: 350px"
              size="medium "
              placeholder="请输入子栏目名"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择父栏目" prop="columnId">
            <el-select
              v-model="formList.columnId"
              placeholder="请选择"
              style="width: 350px"
              size="medium "
            >
              <el-option
                v-for="column in columnList"
                :key="column.id"
                :label="column.columnName"
                :value="column.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-upload
              class="avatar-uploader"
              action="/drug/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <div slot="tip" class="el-upload__tip">
                请上传一张图片（大小不能超1MB,图片格式jpg,jpeg,png）
              </div>
              <img v-if="formList.image" :src="formList.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <Editor v-model="formList.article" :value="formList.article" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页器 
      -->
      <el-pagination
        style="margin-top: 20px; text-align: center"
        :current-page="page"
        @current-change="getList"
        @size-change="handleSizeChange"
        :page-size="limit"
        :page-sizes="[8, 10, 15]"
        layout="prev, pager, next,jumper,->,total,sizes "
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
// 获取vuex的mapGetter方法
import { mapGetters } from "vuex";
export default {
  name: "",
  data() {
    return {
      // 查询表单
      searchList: {
        // 所属栏目
        columnId: "",
        // 发布状态
        releaseStatus: "",
      },
      // 数据列表
      list: [],
      // 表格列表
      tableList: [
        { prop: "title", label: "文章标题", width: "150" },
        { prop: "releaseTime", label: "发布时间", width: "150" },
        { prop: "columnName", label: "所属栏目", width: "100" },
        { prop: "creator", label: "创建者", width: "100" },
      ],
      // 页数
      page: 1,
      // 展示数据条数
      limit: 8,
      // 数据条数
      total: 20,
      // 控制弹窗字段
      dialogVisible: false,
      // 弹窗名
      title: "",
      // 富文本数据
      formList: {
        // 文章
        article: "",
        // 所选栏目
        columnId: "",
        // 	创建者
        creator: "",
        // 图片地址
        image: "",
        // 	文章标题
        title: "",
      },
      // 富文本数据
      content: "",
      // 栏目数据
      columnList: [],
      // 选中后的数据
      deleteList: [],
      // 表单验证
      rules: {
        columnId: [
          { required: true, message: "请选择栏目", trigger: "change" },
        ],
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
      },
    };
  },
  // 组件挂载完毕调用接口
  mounted() {
    this.getList();
    this.getColumnList();
  },
  methods: {
    // 获取数据
    async getList(pager = 1) {
      this.page = pager;
      // 结构vm的数据
      const { page, limit, searchList } = this;
      //重新配置数据
      searchList.pageNum = page;
      searchList.pageSize = limit;
      let result = await this.$API.journalism.reqGetList(searchList);
      if (result.status == 200) {
        this.list = result.data.records;
        this.total = result.data.total;
      }
    },
    // 每页展示条数触发的事件
    handleSizeChange(limit) {
      this.limit = limit;
      this.getList();
    },
    // 获取栏目信息
    async getColumnList() {
      let result = await this.$API.journalism.reqGetAll();
      if (result.status == 200) {
        this.columnList = result.data;
      }
    },
    // 查询按钮
    search() {
      this.getList();
    },
    // 添加新闻按钮
    addNews() {
      this.dialogVisible = true;
      this.title = "新增新闻";
      this.formList = {
        // 文章
        article: "",
        // 所选栏目
        columnId: "",
        // 	创建者
        creator: "",
        // 图片地址
        image: "",
        // 	文章标题
        title: "",
      };
    },
    // 修改新闻按钮
    editNews(row) {
      this.dialogVisible = true;
      this.formList = { ...row };
      this.title = "修改新闻";
    },
    // 关闭弹窗的回调
    handleClose(done) {
      this.$confirm("您还未确认保存，确认退出吗？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 文件上传成功时的钩子
    handleAvatarSuccess({ data }, file) {
      this.formList.image = data.domain + data.path + "?download=0";
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 确认新增 || 修改
    confirm() {
      this.$refs.ruleFrom.validate(async (success) => {
        if (success) {
          let objData = {};
          // 整理数据
          if (this.formList.id) {
            objData.article = this.formList.article;
            objData.columnId = this.formList.columnId;
            objData.id = this.formList.id;
            objData.image = this.formList.image;
            objData.title = this.formList.title;
          } else {
            this.formList.creator = this.username;
            objData = this.formList;
          }
          console.log(objData);
          let result = await this.$API.journalism.reqAddOredit(objData);
          if (result.status == 200) {
            this.$message({
              message: this.formList.id ? "修改成功" : "新增成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.getList(this.formList.id ? this.page : 1);
          }
        } else {
          return false;
        }
      });
    },
    // 修改发布状态
    async release(row) {
      if (row.releaseStatus == 1) {
        this.$prompt("请选择发布时间", "发布时间", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputType: "datetime-local",
        })
          .then(async ({ value }) => {
            var time = "";
            time = value.replace("T", " ") + ":00";
            let result = await this.$API.journalism.reqRelease({
              id: row.id,
              releaseTime: time,
            });
            if (result.status == 200) {
              this.getList(this.page);
              this.$message({
                type: "success",
                message: "发布成功",
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消选择",
            });
          });
      } else {
        let result = await this.$API.journalism.reqRelease({
          id: row.id,
        });
        if (result.status == 200) {
          this.getList(this.page);
          this.$message({
            type: "success",
            message: "已取消发布",
          });
        }
      }
    },
    // 确认删除按钮
    async deleteJourn(row) {
      let result = await this.$API.journalism.reqDelete(row.id);
      if (result.status == 200) {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.getList(this.list.length > 1 ? this.page : this.page - 1);
      }
    },
    // 设为轮播图按钮
    async carousel(row) {
      let result = await this.$API.journalism.reqCarousel({ id: row.id });
      if (result.status == 200) {
        this.getList(this.page);
        this.$message({
          message: row.carouselStatus == 1 ? "设置成功" : "已取消设置",
          type: "success",
        });
      }
    },
    // 设置置顶按钮
    async topOrBottom(row) {
      let result = await this.$API.journalism.reqTopOrBottom({ id: row.id });
      if (result.status == 200) {
        this.getList(this.page);
        this.$message({
          message: row.topStatus == 1 ? "置顶成功" : "已取消置顶",
          type: "success",
        });
      }
    },
    // 是否设置加密
    async encryption(row) {
      // 判断加密状态是否需要加密
      if (row.privacy == 1) {
        this.$prompt("请输入密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          // 正常表达式判断，输入框是否为空
          inputPattern: /\S/,
          inputErrorMessage: "密码不能为空",
        })
          .then(async ({ value }) => {
            // 点击确定调取加密接口
            let result = await this.$API.journalism.reqPrivacy({
              id: row.id,
              pwd: value,
            });
            if (result.status == 200) {
              this.getList(this.page);
              this.$message({
                type: "success",
                message: "设置密码成功",
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      } else {
        // 取消加密
        let result = await this.$API.journalism.reqPrivacy({
          id: row.id,
        });
        if (result.status == 200) {
          this.getList(this.page);
          this.$message({
            type: "success",
            message: "已取消加密",
          });
        }
      }
    },
    // 勾选时的回调
    handleSelectionChange(val) {
      // 重构数据
      this.deleteList = val.map((item) => {
        return item.id;
      });
    },
    // 批量删除按钮
    async deleteInBatches() {
      let result = await this.$API.journalism.reqDeleteInBatches(
        this.deleteList
      );
      if (result.status == 200) {
        this.getList(this.list.length > 1 ? this.page : this.page - 1);
        this.$message({
          message: "批量删除成功",
          type: "success",
        });
      }
    },
  },
  // 计算属性
  computed: {
    // 计算用户名
    ...mapGetters(["username"]),
  },
};
</script>

<style lang="scss" scoped></style>
